package mybatisgen.plugin;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;

import java.util.List;

public class ErsPagePlugin extends PluginAdapter {
    @Override
    public boolean validate(List<String> list) {
        return true;
    }

    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        FullyQualifiedJavaType pageableInterface = new FullyQualifiedJavaType("com.xinmei.ers.core.common.page.Pageable");
        topLevelClass.addImportedType(pageableInterface);
        topLevelClass.addSuperInterface(pageableInterface);

        FullyQualifiedJavaType booleanWrapper = FullyQualifiedJavaType.getBooleanPrimitiveInstance();
        Field limit = new Field("pageable", booleanWrapper);
        limit.setVisibility(JavaVisibility.PRIVATE);
        topLevelClass.addField(limit);

        Method enablePage = new Method("enablePage");
        enablePage.setVisibility(JavaVisibility.PUBLIC);
        enablePage.setReturnType(topLevelClass.getType());
        enablePage.addBodyLine("this.pageable = true;");
        enablePage.addBodyLine("return this;");
        topLevelClass.addMethod(enablePage);

        Method disablePage = new Method("disablePage");
        disablePage.setVisibility(JavaVisibility.PUBLIC);
        disablePage.setReturnType(topLevelClass.getType());
        disablePage.addBodyLine("this.pageable = false;");
        disablePage.addBodyLine("return this;");
        topLevelClass.addMethod(disablePage);

        Method isPageable = new Method("isPageable");
        isPageable.setVisibility(JavaVisibility.PUBLIC);
        isPageable.setReturnType(booleanWrapper);
        isPageable.addBodyLine("return pageable;");
        topLevelClass.addMethod(isPageable);

        return true;
    }

    private static final String PAGE_LIST_CLASS = "com.xinmei.ers.core.common.page.PageList";
    @Override
    public boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        processPageList(method, interfaze);
        return super.clientSelectByExampleWithBLOBsMethodGenerated(method, interfaze, introspectedTable);
    }

    @Override
    public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        processPageList(method, interfaze);
        return super.clientSelectByExampleWithoutBLOBsMethodGenerated(method, interfaze, introspectedTable);
    }

    private void processPageList(Method method, Interface interfaze) {
        interfaze.addImportedType(new FullyQualifiedJavaType(PAGE_LIST_CLASS));
        method.setReturnType(new FullyQualifiedJavaType(PAGE_LIST_CLASS + method.getReturnType().get().getFullyQualifiedName().substring("java.util.List".length())));
    }
}